import { ref, onMounted, reactive } from 'vue'
import Map from '/@/utils/rw/map'
import { useMessage } from '/@/hooks/web/useMessage'
const { createMessage: msg } = useMessage()
import { defHttp } from '/@/utils/http/axios'
import { getToken } from '/@/utils/auth'
import Sub from './sub'
enum API {
	mapInfo = 'Maps/Detailed',
	realPosition = 'locations/indoor/GetRealtime',
}
interface IMapOptions {
	el: string
	mapListApi?: string
	mapId?: string
}

export const useMap = (options: IMapOptions) => {
	let map = reactive<any>(null)
	const windowInstance: any = window
	const token: string = getToken()
	let timer = null

	map = new Map(options.el)
	if (options.mapId) {
		loadMap({ id: options.mapId })
	}

	function loadMap(obj) {
		// defHttp.get({ url: `${API.mapInfo}`, params: { id: options.mapId } }).then(res => {
		// })
		map
			.loadMap({
				imageFullUrl: `${windowInstance.config.base_url}/Maps/pic/${obj.id}?access_token=${token}`,
				width: 50,
				height: 50,

				code: obj.code,
			})
			.catch((err) => {
				msg.error('地图文件加载失败')
			})
	}

	function initPosition(params, cb) {
		clearTimeout(timer)
		let positionTime: number = windowInstance.config.position_time || 2000
		let func = async () => {
			let res
			res = await defHttp.get({ url: API.realPosition, params })
			if (params.search && !res.data.length) {
				delete params.MapId
				res = await defHttp.get({ url: API.realPosition, params })
				if (res.data.length) {
					let mapCode = res.data[0].mapCode
					// let oldMapCode = map.mapObj.code
					// if (mapCode != oldMapCode) {
					Sub.$trigger('toogleMap', { key: '', item: { code: mapCode }, tagCode: params.TeId })
					// }
				}
			}
			map.position(res.data)
			// Sub.$trigger('position', res.data)
			timer = setTimeout(func, positionTime)
		}
		func()
	}

	function stop() {
		clearInterval(timer)
	}

	function setArea(points: []) {
		if (!points.length) return
		map.loadArea(points)
	}
	function setHistoryLine(data) {
		map.setHistoryLine(data)
	}
	return {
		position: {},
		area: {
			setArea,
		},
		history: {
			setHistoryLine,
		},
		common: {
			loadMap,
			initPosition,
			stop,
		},
		map,
	}
}
